import re
import json


# 定义一个字典来存储常见问题和对应的回答
responses = {}


def load_responses():
    try:
        with open('responses.json', 'r', encoding='utf - 8') as f:
            global responses
            responses = json.load(f)
    except FileNotFoundError:
        pass


def save_responses():
    with open('responses.json', 'w', encoding='utf - 8') as f:
        json.dump(responses, f, ensure_ascii=False, indent=4)


def simple_chatbot(user_input):
    # 检查是否是数学计算
    match = re.search(r'(\d+)\s*([+\-*/%])\s*(\d+)', user_input)
    if match:
        num1 = float(match.group(1))
        operator = match.group(2)
        num2 = float(match.group(3))
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '*':
            result = num1 * num2
        elif operator == '/':
            if num2 != 0:
                result = num1 / num2
            else:
                return "除数不能为零"
        elif operator == '%':
            result = num1 % num2
        return f"计算结果是: {result}"

    for key in responses.keys():
        if key in user_input:
            import random
            return random.choice(responses[key])
    return "我不太明白你的意思，可以换个说法吗？"


def update_responses(question, answer):
    if question in responses:
        responses[question].append(answer)
    else:
        responses[question] = [answer]


if __name__ == "__main__":
    load_responses()
    while True:
        user_input = input("你: ").strip()
        if user_input.lower() == '退出':
            save_responses()
            break
        response = simple_chatbot(user_input)
        print("聊天机器人: ", response)
        feedback = input("请输入反馈（直接回车表示满意，否则输入新回答）: ").strip()
        if feedback:
            update_responses(user_input, feedback)
